package com.unknowpupil.web.service.impl;

import com.unknowpupil.web.base.impl.BaseCrudServiceImpl;
import com.unknowpupil.web.domain.AccountInfo;
import com.unknowpupil.web.domain.Currencies;
import com.unknowpupil.web.domain.Wallet;
import com.unknowpupil.web.exception.MxException;
import com.unknowpupil.web.mapper.WalletMapper;
import com.unknowpupil.web.service.ICurrenciesService;
import com.unknowpupil.web.service.IWalletService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Classname: IWalletService
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2019/11/6 12:00
 * @Description:
 * @Version: 1.0
 */
@Service
@Transactional(readOnly = true)
public class WalletServiceImpl extends BaseCrudServiceImpl<Wallet, WalletMapper> implements IWalletService {
    @Mapper
    private WalletMapper walletMapper;
    @Autowired
    private ICurrenciesService currenciesService;
    @Override
    public Wallet getWalletByCurrencyAndAddress(String eth, String to) {
        Example example  = new Example(Wallet.class);
        example.createCriteria().andEqualTo("address", to)
                .andEqualTo("currency", eth);
        Wallet wallet = walletMapper.selectOneByExample(example);
        return wallet;
    }
    @Override
    public boolean createWallet(AccountInfo accountInfo) throws MxException {
        List<Currencies> currencies = currenciesService.getCurrencies();
        currencies.forEach(currency->{
            if(currency.getDelFalg()!=0){
                if(currency.getStatus()==0){
                    if(currency.getIsCreate()==0){
                        Wallet wallet = new Wallet();
                        //以太链
                        if(currency.getLine()==0){
                            wallet.setCurrency(currency.getCurrency());
                            wallet.setAddress(accountInfo.getEthAddress());
                            wallet.setPrivateKey(accountInfo.getEthPrivateKey());
                        }
                        //比特链
                        else {
                            wallet.setCurrency(currency.getCurrency());
                            wallet.setAddress(accountInfo.getBtcAddress());
                            wallet.setPrivateKey(accountInfo.getBtcPrivateKey());
                        }
                        wallet.setBalance(new BigDecimal(0.0));
                        wallet.setFreezeBalance(new BigDecimal(0.0));
                        wallet.setUserId(accountInfo.getUserId());
                        wallet.setDelFlag(0);
                        wallet.setStatus(0);
                        save(wallet);
                    }
                }
            }
        });

        return true;
    }
}
